<?php
/**
 * Copyright (c) 2006, PORTALIER Julien
 * 
 * Licensed under The LGPL License
 * Redistributions of files must retain the above copyright notice.
 * 
 * @package      Feather-CM
 * @subpackage   Auth
 * @copyright    Copyright (c) 2006, Julien PORTALIER
 * @link         http://julien.portalier.com
 * @license      http://www.opensource.org/licenses/lgpl-license.php The LGPL License
 * 
 * @requires     AuthComponent
 */

class AclComponent
{
	protected $id;
	protected $groups;
	
	/*protected $Perms;*/
	
	function startup(Controller $controller)
	{
		$this->Auth = $controller->auth;
	}
	
	function checkAccess($aco, $action)
	{
		if (!$this->check($aco, null, $action))
			$this->Auth->permissionDenied();
	}
	
	function check($aco=null, $aro=null, $action="read")
	{
		if (Config::power_privileges and $this->Auth->inGroup('administrator'))
			return true;
		
		$conditions = array('Aco.aco'=>$aco);
		if (!is_null($aro))
			$conditions['Aro.aro'] = $aro;		
		
		$roles = $this->Perms->fetchRoles(&$conditions);
		
		// restricted access? checking rules
		if (!empty($roles))
		{
			// user specific rule?
			if (isset($roles["User.{$this->Auth->id}"]))
				return $roles["User.{$this->Auth->id}"][$action] ? true : false;
			
			// groups rules
			$right = null;
			foreach ($this->Auth->groups as $grp)
			{
				if (isset($roles["Group.$grp"]))
				{
					$right = $roles["Group.$grp"][$action];
					
					// access granted?
					if ($right) return true;
				}
			}
			if (!is_null($right))
				return $right ? true : false;
			
			// default rule?
			if (isset($roles['Group.all']))
				return $roles['Group.all'][$action] ? true : false;
			
			// access denied!
			return false;
		}
		
		// returns an undefined state
		return null;
	}
	
	// admin
	
	function registerAro($aro)
	{
		$this->Perms->Aro->create($aro);
	}
	
	function grant($aro, $aco, $action='*', $value=true)
	{
		if ($action == '*')
		{
			$read   = $value;
			$write  = $value;
			$delete = $value;
		}
		else
		{
			foreach (explode(',', $action) as $action)
			{
				$action = trim($action);
				${$action} = $value;
			} 
		}
		return $this->Perms->create($aro, $aco,
			isset($read)   ? $read   : null,
			isset($write)  ? $write  : null,
			isset($delete) ? $delete : null
		);
	}
	
	function revoke($aro, $aco, $action='*') {
		return $this->grant($aro, $aco, $action, false);
	}
	
	function allow($aro, $aco, $action='*') {
		return $this->grant($aro, $aco, $action, true);
	}
	
	function deny($aro, $aco, $action='*') {
		return $this->grant($aro, $aco, $action, false);
	}
	
	// overrides
	
	protected function __get($name)
	{
		if ($name == 'Perms')
		{
			require_once FEATHER.'controllers'.DS.'components'.DS.'acl'.DS.'aclnode.php';
			require_once FEATHER.'controllers'.DS.'components'.DS.'acl'.DS.'aros_aco.php';
			$this->Perms = new ArosAco;
			return $this->Perms;
		}
		return false;
	}
}
?>